<template>
  <view class="detail-container">
    <!-- 顶部状态栏 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-header">
      <view class="back-btn" @click="goBack">
        <image class="back-icon" src="https://i.ibb.co/nq8B8z3P/comeback.png" mode="aspectFit"></image>
      </view>
      <view class="page-title">试衣详情</view>
      <view class="more-btn" @tap="showMore">
        <text class="more-dots">⋮</text>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 详情内容 -->
    <scroll-view v-else class="detail-content" scroll-y="true">
      <!-- 主图区域 -->
      <view class="main-image-area">
        <image 
          class="main-image" 
          :src="getValidImageUrl(recordDetail.image_url || recordDetail.image)" 
          mode="aspectFit" 
          @error="handleImageError($event, '主图')"
          @tap="previewImage(recordDetail.image_url || recordDetail.image)"
        ></image>
      </view>
      
      <!-- 信息区域 -->
      <view class="info-section">
        <view class="info-header">
          <view class="type-icon">{{ getStyleIcon(recordDetail.title) }}</view>
          <text class="record-title">{{ recordDetail.title }}</text>
          <text class="record-date">{{ formatDate(recordDetail.create_time || recordDetail.created_at) }}</text>
        </view>
        
        <!-- 描述 -->
        <view class="description-block">
          <text class="section-title">今日运势</text>
          <text class="description-text">{{ recordDetail.des || recordDetail.description || '暂无描述' }}</text>
        </view>
        
        <!-- 标签 - 修改为分两行显示 -->
        <view class="tags-block">
          <!-- 适合标签 -->
          <view class="tag-section">
            <text class="tag-category">推荐</text>
            <view class="tags-container">
              <text 
                v-for="(tag, index) in parseTags(recordDetail.suitable)" 
                :key="'suit-'+index" 
                class="tag premium-tag"
              >{{ tag }}</text>
              <text v-if="!parseTags(recordDetail.suitable).length" class="empty-tag">暂无数据</text>
            </view>
          </view>
          
          <!-- 不适合标签 -->
          <view class="tag-section">
            <text class="tag-category">注意</text>
            <view class="tags-container">
              <text 
                v-for="(tag, index) in parseTags(recordDetail.not_suitable)" 
                :key="'not-'+index" 
                class="tag gray-tag"
              >{{ tag }}</text>
              <text v-if="!parseTags(recordDetail.not_suitable).length" class="empty-tag">暂无数据</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 分享区域 -->
      <view class="share-section">
        <view class="share-title">分享给好友</view>
        <view class="share-options">
          <view class="share-option" @tap="shareToWechat">
            <view class="share-icon wechat">
              <text>微信</text>
            </view>
            <text class="share-text">微信</text>
          </view>
          <view class="share-option" @tap="shareToMoments">
            <view class="share-icon moments">
              <text>朋友圈</text>
            </view>
            <text class="share-text">朋友圈</text>
          </view>
          <view class="share-option" @tap="saveImage">
            <view class="share-icon save">
              <text>保存</text>
            </view>
            <text class="share-text">保存图片</text>
          </view>
        </view>
      </view>
      
      <!-- 推荐区域 -->
      <view class="recommendation-section">
        <view class="section-header">
          <text class="section-title">相似穿搭推荐</text>
          <text class="view-all" @tap="viewMoreRecommendations">查看更多</text>
        </view>
        
        <scroll-view class="recommendation-scroll" scroll-x="true">
          <view 
            class="recommendation-item" 
            v-for="(item, index) in recommendations" 
            :key="index"
            @tap="viewRecommendationDetail(item)"
          >
            <image class="recommendation-image" :src="getValidImageUrl(item.image_url || item.image)" mode="aspectFill"></image>
            <text class="recommendation-title">{{ item.title }}</text>
          </view>
        </scroll-view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 20,
      recordId: null,
      loading: true,
      recordDetail: {
        id: 0,
        title: '',
        image: '',
        description: '',
        tags: '',
        created_at: '',
        updated_at: ''
      },
      recommendations: []
    }
  },
  onLoad(options) {
    // 获取状态栏高度
    this.getSystemInfo();
    
    // 获取记录ID
    if (options && options.id) {
      this.recordId = options.id;
      this.loadRecordDetail();
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        this.goBack();
      }, 1500);
    }
  },
  methods: {
    // 获取系统信息
    getSystemInfo() {
      try {
        // 使用推荐的新API替代弃用的getSystemInfoSync
        const systemInfo = uni.getWindowInfo();
        this.statusBarHeight = systemInfo.statusBarHeight || 20;
      } catch (e) {
        console.error('获取系统信息失败', e);
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1,
        fail: () => {
          uni.redirectTo({
            url: '/pages/AI_try_on/history'
          });
        }
      });
    },
    
    // 加载记录详情
    loadRecordDetail() {
      this.loading = true;
      
      // 使用项目实际的API域名
      const apiBaseUrl = 'https://test.zysemtime.com';
      
      // 获取全局配置的URL，如果为空则使用硬编码值
      const globalBaseUrl = getApp().globalData.HTTP_REQUEST_URL;
      console.log('全局配置的基础URL:', globalBaseUrl);
      
      // 如果全局URL存在，则使用全局URL，否则使用硬编码的URL
      const fullApiUrl = globalBaseUrl ? 
        (globalBaseUrl + '/api/dress_history/get/' + this.recordId) : 
        (apiBaseUrl + '/api/dress_history/get/' + this.recordId);
      
      console.log('使用的完整API URL:', fullApiUrl);
      console.log('正在获取记录ID:', this.recordId);
      
      uni.request({
        url: fullApiUrl,
        method: 'GET',
        header: {
          'Authorization': uni.getStorageSync('token')
        },
        success: (res) => {
          console.log('获取记录详情成功:', JSON.stringify(res.data, null, 2));
          
          if (res.data && res.data.code === 200 && res.data.data) {
            this.recordDetail = res.data.data;
            console.log('记录详情数据:', this.recordDetail);
            
            // 检查图片字段
            if (this.recordDetail.image_url) {
              console.log('图片URL(image_url):', this.recordDetail.image_url);
            } else if (this.recordDetail.image) {
              console.log('图片URL(image):', this.recordDetail.image);
            } else {
              console.warn('记录中没有找到有效的图片URL');
            }
            
            // 检查标签字段
            console.log('适合标签(suitable):', this.recordDetail.suitable);
            console.log('不适合标签(not_suitable):', this.recordDetail.not_suitable);
            
            // 加载推荐数据
            this.loadRecommendations();
          } else {
            uni.showToast({
              title: res.data?.message || '获取记录详情失败',
              icon: 'none',
              duration: 2000
            });
            
            setTimeout(() => {
              this.goBack();
            }, 1500);
          }
        },
        fail: (err) => {
          console.error('获取记录详情失败:', err);
          console.error('错误详情:', JSON.stringify(err, null, 2));
          
          uni.showToast({
            title: '网络请求失败，请稍后再试',
            icon: 'none',
            duration: 2000
          });
          
          setTimeout(() => {
            this.goBack();
          }, 1500);
        },
        complete: () => {
          this.loading = false;
        }
      });
    },
    
    // 加载推荐数据
    loadRecommendations() {
      // 使用项目实际的API域名
      const apiBaseUrl = 'https://test.zysemtime.com';
      
      // 获取全局配置的URL，如果为空则使用硬编码值
      const globalBaseUrl = getApp().globalData.HTTP_REQUEST_URL;
      
      // 如果全局URL存在，则使用全局URL，否则使用硬编码的URL
      const fullApiUrl = globalBaseUrl ? 
        (globalBaseUrl + '/api/dress_history/list') : 
        (apiBaseUrl + '/api/dress_history/list');
      
      console.log('推荐列表API URL:', fullApiUrl);
      
      // 获取相似穿搭推荐
      uni.request({
        url: fullApiUrl,
        method: 'GET',
        data: {
          page: 1,
          limit: 5,
          exclude_id: this.recordId // 排除当前记录
        },
        header: {
          'Authorization': uni.getStorageSync('token')
        },
        success: (res) => {
          console.log('获取推荐数据成功:', JSON.stringify(res.data, null, 2));
          
          if (res.data && res.data.code === 200 && res.data.data && res.data.data.data) {
            this.recommendations = res.data.data.data;
          }
        },
        fail: (err) => {
          console.error('获取推荐数据失败:', err);
          console.error('错误详情:', JSON.stringify(err, null, 2));
        }
      });
    },
    
    // 获取有效的图片URL
    getValidImageUrl(url) {
      if (!url) return '/static/easy-loadimage/loading.png';
      
      console.log('处理图片URL:', url);
      
      // 如果URL已经是完整URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 如果URL是相对路径，添加基础URL
      const baseUrl = getApp().globalData.HTTP_REQUEST_URL || 'https://test.zysemtime.com';
      const formattedUrl = url.startsWith('/') ? url.substring(1) : url;
      const fullUrl = `${baseUrl}/${formattedUrl}`;
      
      console.log('完整URL:', fullUrl);
      return fullUrl;
    },
    
    // 处理图片加载错误
    handleImageError(e, type) {
      console.log(`${type}图片加载失败`, e);
      // 设置默认图片
      const defaultImg = '/static/easy-loadimage/loading.png';
      
      // 获取当前图片元素
      const currentTarget = e.currentTarget;
      if (currentTarget) {
        // 在小程序环境中，通过currentTarget更新图片src
        currentTarget.src = defaultImg;
      }
    },
    
    // 预览图片
    previewImage(url) {
      if (!url) return;
      
      uni.previewImage({
        urls: [url],
        current: url,
        indicator: 'number',
        loop: false
      });
    },
    
    // 显示更多操作
    showMore() {
      uni.showActionSheet({
        itemList: ['删除记录', '举报'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.deleteRecord();
          } else if (res.tapIndex === 1) {
            uni.showToast({
              title: '举报功能开发中',
              icon: 'none'
            });
          }
        }
      });
    },
    
    // 删除记录
    deleteRecord() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmColor: '#ff5c8d',
        success: (res) => {
          if (res.confirm) {
            // 获取基础URL
            const baseUrl = getApp().globalData.HTTP_REQUEST_URL || '';
            
            uni.request({
              url: `${baseUrl}/api/dress_history/delete/${this.recordId}`,
              method: 'DELETE',
              header: {
                'Authorization': uni.getStorageSync('token')
              },
              success: (result) => {
                if (result.data && result.data.code === 200) {
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success',
                    duration: 2000
                  });
                  
                  // 标记需要刷新历史页面
                  getApp().globalData.needRefreshHistory = true;
                  
                  setTimeout(() => {
                    this.goBack();
                  }, 1500);
                } else {
                  uni.showToast({
                    title: result.data?.message || '删除失败',
                    icon: 'none',
                    duration: 2000
                  });
                }
              },
              fail: (err) => {
                console.error('删除记录失败:', err);
                uni.showToast({
                  title: '网络请求失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          }
        }
      });
    },
    
    // 分享到微信
    shareToWechat() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    },
    
    // 分享到朋友圈
    shareToMoments() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    },
    
    // 保存图片
    saveImage() {
      if (!this.recordDetail.image) {
        uni.showToast({
          title: '没有可保存的图片',
          icon: 'none'
        });
        return;
      }
      
      uni.downloadFile({
        url: this.recordDetail.image,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({
                  title: '图片已保存',
                  icon: 'success'
                });
              },
              fail: (err) => {
                console.error('保存图片失败:', err);
                if (err.errMsg.includes('auth deny')) {
                  uni.showModal({
                    title: '保存失败',
                    content: '请授权保存图片到相册的权限',
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        uni.openSetting();
                      }
                    }
                  });
                } else {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  });
                }
              }
            });
          } else {
            uni.showToast({
              title: '下载图片失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '下载图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 查看更多推荐
    viewMoreRecommendations() {
      uni.redirectTo({
        url: '/pages/AI_try_on/history'
      });
    },
    
    // 查看推荐详情
    viewRecommendationDetail(item) {
      uni.navigateTo({
        url: `/pages/AI_try_on/history_detail?id=${item.id}`
      });
    },
    
    // 解析标签字符串
    parseTags(tagsStr) {
      if (!tagsStr) return [];
      
      try {
        // 如果标签是字符串，则尝试解析
        if (typeof tagsStr === 'string') {
          // 先尝试解析为JSON
          try {
            const parsed = JSON.parse(tagsStr);
            if (Array.isArray(parsed)) {
              return parsed;
            } else {
              return [tagsStr];
            }
      } catch (e) {
            // 如果不是JSON格式，按照逗号或顿号分隔
            if (tagsStr.includes('、') || tagsStr.includes(',')) {
              let separators = tagsStr.includes('、') ? '、' : ',';
              return tagsStr.split(separators).map(tag => tag.trim()).filter(tag => tag);
            } else {
        return [tagsStr];
            }
          }
        } 
        
        // 如果已经是数组，直接返回
        if (Array.isArray(tagsStr)) {
          return tagsStr;
        }
        
        return [];
      } catch (e) {
        console.error('解析标签出错:', e);
        return [];
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      try {
        const date = new Date(dateStr);
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
      } catch (e) {
        return dateStr;
      }
    },
    
    // 根据标题获取对应的图标
    getStyleIcon(title) {
      if (!title) return '👔';
      
      if (title.includes('约会')) return '❤️';
      if (title.includes('休闲')) return '☕';
      if (title.includes('商务')) return '👔';
      if (title.includes('旅行')) return '✈️';
      if (title.includes('聚会')) return '🎉';
      if (title.includes('运动')) return '🏃';
      
      return '👔';
    }
  }
}
</script>

<style lang="scss">
.detail-container {
  min-height: 100vh;
  background-color: #fff5f8;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx; // 为底部按钮留出空间
}

.status-bar {
  width: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.nav-header {
  height: 90rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 0 30rpx;
  position: relative;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  backdrop-filter: blur(10px);
}

.back-btn {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 35rpx;
  height: 35rpx;
  opacity: 0.8;
}

.page-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  letter-spacing: 1.5rpx;
}

.more-btn {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-dots {
  font-size: 40rpx;
  line-height: 40rpx;
  color: #666;
  transform: rotate(90deg);
}

.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(255, 107, 157, 0.2);
  border-top: 4rpx solid #ff6b9d;
  border-radius: 50%;
  animation: spin 1s infinite linear;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.detail-content {
  flex: 1;
}

.main-image-area {
  width: 100%;
  height: 750rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.type-icon {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  background-color: rgba(255, 107, 157, 0.1);
  border-radius: 50%;
  margin-right: 20rpx;
}

.record-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.record-date {
  font-size: 24rpx;
  color: #999;
}

.description-block, .tags-block {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
  display: block;
}

.description-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.tags-block {
  margin-bottom: 30rpx;
}

.tag-section {
  margin-bottom: 20rpx;
}

.tag-category {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
  font-weight: 500;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.tag {
  font-size: 24rpx;
  color: #666;
  background-color: rgba(245, 245, 245, 0.8);
  padding: 8rpx 20rpx;
  border-radius: 25rpx;
  margin: 0 10rpx 15rpx 10rpx;
}

.empty-tag {
  font-size: 24rpx;
  color: #999;
  font-style: italic;
  padding: 8rpx 0;
}

.premium-tag {
  color: #e83e8c;
  background: linear-gradient(to right, rgba(255, 240, 245, 0.9), rgba(255, 228, 238, 0.9));
  border: 1px solid rgba(255, 182, 193, 0.3);
  box-shadow: 0 2rpx 6rpx rgba(255, 105, 180, 0.1);
  padding: 8rpx 18rpx;
  font-weight: 500;
  letter-spacing: 0.8rpx;
  position: relative;
  overflow: hidden;
}

.gray-tag {
  color: #999;
  background-color: rgba(245, 245, 245, 0.8);
}

.share-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.share-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 25rpx;
}

.share-options {
  display: flex;
  justify-content: space-around;
}

.share-option {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
  font-size: 24rpx;
  color: #fff;
  
  &.wechat {
    background-color: #07c160;
  }
  
  &.moments {
    background-color: #1aad19;
  }
  
  &.save {
    background-color: #1296db;
  }
}

.share-text {
  font-size: 24rpx;
  color: #666;
}

.recommendation-section {
  background-color: #fff;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25rpx;
}

.view-all {
  font-size: 24rpx;
  color: #ff6b9d;
}

.recommendation-scroll {
  white-space: nowrap;
  width: 100%;
}

.recommendation-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
}

.recommendation-image {
  width: 200rpx;
  height: 250rpx;
  border-radius: 15rpx;
  margin-bottom: 10rpx;
}

.recommendation-title {
  font-size: 24rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 